<template>
  <el-form
    label-width="100px"
    :model="skuInfo"
    ref="ruleFormRef"
    :rules="rules"
  >
    <el-form-item label="SPU名称">{{ props.spu.spuName }}</el-form-item>
    <el-form-item label="SKU名称" prop="skuName">
      <el-input v-model="skuInfo.skuName" type="text" />
    </el-form-item>
    <el-form-item label="价格(元)" prop="price">
      <el-input-number
        class="mx-4"
        v-model="skuInfo.price"
        style="width: 100%"
        :min="1"
        :max="10000"
        controls-position="right"
      />
    </el-form-item>
    <el-form-item label="重量(克)" prop="weight">
      <el-input-number
        class="mx-4"
        v-model="skuInfo.weight"
        style="width: 100%"
        :min="1"
        :max="100000"
        controls-position="right"
      />
    </el-form-item>
    <el-form-item label="规格描述" prop="skuDesc">
      <el-input v-model="skuInfo.skuDesc" type="textarea" rows="4" />
    </el-form-item>
    <el-form-item label="平台属性" prop="skuAttrValueList">
      <el-row :gutter="20">
        <el-col
          :md="12"
          :sm="12"
          :xs="24"
          :lg="8"
          style="margin-bottom: 15px"
          v-for="(skuAttr, index) in attrList"
          :key="skuAttr.id"
        >
          <el-form-item :label="skuAttr.attrName">
            <el-select
              placeholder="请选择"
              v-model="skuInfo.skuAttrValueList[index]"
            >
              <el-option
                v-for="attrValue in skuAttr.attrValueList"
                :key="attrValue.id"
                :label="attrValue.valueName"
                :value="`${skuAttr.id}:${skuAttr.attrName}:${attrValue.id}:${attrValue.valueName}`"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form-item>
    <el-form-item label="销售属性" prop="skuSaleAttrValueList">
      <el-row :gutter="20">
        <el-col
          style="margin-bottom: 15px"
          v-for="(saleAttr, index) in spuSaleAttrList"
          :key="saleAttr.id"
        >
          <el-form-item :label="saleAttr.saleAttrName">
            <el-select
              placeholder="请选择"
              v-model="skuInfo.skuSaleAttrValueList[index]"
            >
              <el-option
                v-for="saleAttrValue in saleAttr.spuSaleAttrValueList"
                :key="saleAttrValue.id"
                :label="saleAttrValue.saleAttrValueName"
                :value="`${saleAttr.id}:${saleAttr.saleAttrName}:${saleAttrValue.id}:${saleAttrValue.saleAttrValueName}`"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form-item>
    <el-form-item label="图片列表" prop="skuImageList">
      <el-table
        style="width: 100%"
        @selection-change="handleSelectionChange"
        border
        :data="spuImageList"
      >
        <el-table-column type="selection" width="50" />
        <el-table-column label="图片">
          <template #default="{ row }">
            <el-image :src="row.imgUrl" style="width: 100px" />
          </template>
        </el-table-column>
        <el-table-column label="名称" prop="imgName" />
        <el-table-column label="操作">
          <template #default="{ row }">
            <el-button
              type="primary"
              v-if="row.isDefault === '0'"
              @click="setDefaultImg(row)"
              >设置默认</el-button
            >
            <el-button type="success" v-else @click="row.isDefault = '0'"
              >默认</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="submitForm(ruleFormRef)"
        >保存</el-button
      >
      <el-button @click="emits('getScene', 1)">取消</el-button>
    </el-form-item>
  </el-form>
</template>

<script lang="ts">
export default {
  name: 'SkuForm',
}
</script>
<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue'
import type { FormRules, FormInstance } from 'element-plus'
import { ElMessage } from 'element-plus'
import { reqSpuSaleAttrList, reqSpuImgListData } from '@/api/product/spu'
import { reqGetAttrInfoListData } from '@/api/product/attr'
import { reqSaveSkuInfo } from '@/api/product/sku'
import { useCategoryStore } from '@/stores/category'
const props = defineProps(['spu'])
// 定义三个变量来存储响应回来的数据
const spuImageList = ref([])
const spuSaleAttrList = ref([])
const attrList = ref([])
const skuInfo = reactive({
  skuName: '',
  price: 0,
  weight: 0,
  skuDesc: '',
  skuDefaultImg: '',
  skuAttrValueList: [],
  skuSaleAttrValueList: [],
  skuImageList: [],
})
const emits = defineEmits(['getScene'])
const categoryStore = useCategoryStore()

// 表单校验
const ruleFormRef = ref<FormInstance>()
const rules = reactive<FormRules>({
  skuName: [
    {
      type: 'string',
      required: true,
      message: '请输入SKU名称',
      trigger: 'blur',
      transform(value) {
        return value.trim()
      },
    },
  ],
  price: [
    {
      required: true,
      message: '请输入产品价格',
      trigger: 'blur',
    },
  ],
  weight: [
    {
      required: true,
      message: '请输入产品重量',
      trigger: 'blur',
    },
  ],
  skuDesc: [
    {
      type: 'string',
      required: true,
      message: '请输入SKU描述',
      trigger: 'blur',
      transform(value) {
        return value.trim()
      },
    },
  ],
  skuAttrValueList: [
    {
      type: 'array',
      required: true,
      message: '请选择平台属性',
      trigger: 'change',
    },
  ],
  skuSaleAttrValueList: [
    {
      type: 'array',
      required: true,
      message: '请选择销售属性',
      trigger: 'change',
    },
  ],
  skuImageList: [
    {
      type: 'array',
      required: true,
      message: '请选择SKU图片并设置一张为默认图片',
      trigger: 'change',
      transform(value) {
        const hasDefaultImg = value.some((item) => {
          return item.isDefault === '1'
        })
        return hasDefaultImg ? value : []
      },
    },
  ],
})

const getSkuListData = async () => {
  const promises = [
    reqSpuSaleAttrList(props.spu.id),
    reqGetAttrInfoListData(
      categoryStore.category1Id,
      categoryStore.category2Id,
      categoryStore.category3Id
    ),
    reqSpuImgListData(props.spu.id),
  ]
  const [resSkuSaleAttrValueList, resAttrInfoList, resSpuImgList] =
    await Promise.allSettled(promises)
  spuSaleAttrList.value = resSkuSaleAttrValueList.value
  attrList.value = resAttrInfoList.value
  spuImageList.value = resSpuImgList.value.map((item) => {
    return {
      ...item,
      isDefault: '0',
    }
  })
}

onMounted(() => {
  getSkuListData()
})

//图片选中效果事件函数
const handleSelectionChange = (val) => {
  skuInfo.skuImageList = val
}

//设置默认图片
const setDefaultImg = (row) => {
  skuInfo.skuImageList.forEach((item) => {
    item.isDefault = '0'
  })
  row.isDefault = '1'
  skuInfo.skuDefaultImg = row.imgUrl
}

// 提交表单事件
const submitForm = async (formEl: FormInstance | undefined) => {
  console.log(formEl, 111)
  if (!formEl) return
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      skuInfo.skuAttrValueList = skuInfo.skuAttrValueList
        .filter(Boolean)
        .map((item) => {
          const [attrId, attrName, valueId, valueName] = item.split(':')
          return {
            attrId,
            attrName,
            valueId,
            valueName,
          }
        })
      skuInfo.skuSaleAttrValueList = skuInfo.skuSaleAttrValueList.filter(Boolean).map(item=>{
        const [saleAttrId,saleAttrName,saleAttrValueId,saleAttrValueName] = item.split(':')
        return {
          saleAttrId,saleAttrName,saleAttrValueId,saleAttrValueName
        }
      })
      skuInfo.category3Id = categoryStore.category3Id
      skuInfo.spuId = props.spu.id
      await reqSaveSkuInfo(skuInfo)
      ElMessage.success('添加Sku成功...')
      // 跳转到列表页
      emits('getScene',1)
    } else {
      ElMessage.error('提交失败...')
    }
  })
}
</script>

<style></style>
